import axios from "axios";
import Util from "@/common/utils";
import api from "@/api/apiPath";
import * as qiniu from "qiniu-js";

class MyUploadAdapter {
  constructor(loader) {
    this.loader = loader;
  }

  async upload() {
    const tokenRse = await loadQiniuToken();
    const file = await this.loader.file;
    const token = tokenRse.data.data.imgToken;
    const qiniuUrl = tokenRse.data.data.qiniuUrl;
    const fileName = file.name;
    const postfix = fileName.substring(
      fileName.lastIndexOf("."),
      fileName.length
    );
    const name = Util.getTimeString2(new Date().getTime());

    const putExtra = {
      fname: fileName,
      params: {},
      mimeType: null
    };
    const config = {
      useCdnDomain: true
    };
    const observable = qiniu.upload(
      file,
      name + postfix,
      token,
      putExtra,
      config
    );
    return new Promise((resolve, reject) => {
      observable.subscribe(
        function (res) {
          console.log("图片上传进度：", res);
        },
        function (error) {
          console.error("图片上传失败：", error);
        },
        function (res) {
          const imgUrl = qiniuUrl + res.key;
          resolve({
            default: imgUrl
          });
        }
      );
    });
  }
  abort() {}
}

function loadQiniuToken() {
  return axios.post(api.UPLOADTOKEN, {});
}
export default MyUploadAdapter;
